var _last_router = "";
var _router_tab;
var _editor;
var _timer;
var _ajax_parameter = "";

if(typeof(window.ajaxRef) != "undefined" && typeof(window.ajaxRef.abort) == "function") window.ajaxRef.abort();
window.ajaxRef = undefined;

$(function() {
    $(window).hashchange(function() {
        if(!location.hash || location.hash == "#") {
            location.hash = "home";
            return;
        }
        if(location.hash || location.hash != "#" && location.hash.substr(1) != _last_router) {
            _last_router = location.hash.substr(1);
            _ajax_parameter = "";
            if (_timer !== undefined) clearInterval(_timer);
            _timer = undefined;
            var mod_tag = location.hash.match(/^#([a-z0-9A-Z_]+)/);
            var cursor;
            for(i in _router_tab) {
                if(_router_tab[i].tag == mod_tag[1]) {
                    cursor = i;
                    break;
                }
            }
            if(cursor === undefined) {
                alert("Cannot reach URL. Check your address bar parameters please.");
                return;
            }
            $("#main-content").html("<section><div class=\"round-combo\">Retrieving resources, please wait...</div></section>");
            //$("#main-content").fadeOut(200);
            $(".nav-collapse li").removeClass("active");
            $(".sidebar-nav li").removeClass("active");
            $(".nav-collapse li:eq(" + _router_tab[cursor].navID + ")").addClass("active");
            $(".sidebar-nav li:eq(" + _router_tab[cursor].sideID + ")").addClass("active");
            document.title = _router_tab[cursor].title + " - Welcome to NIT Online Judge";
            if(typeof(window.ajaxRef) !== "undefined" && typeof(window.ajaxRef.abort) == "function") window.ajaxRef.abort();
            window.ajaxRef = $.ajax({
                url: _router_tab[cursor].url + "?r=" + Math.random(),
                success: function(data) {
                    $("#main-content").html(data);
                    //$("#main-content").fadeIn(200);
                    if(_router_tab[cursor].onDraw !== undefined) eval(_router_tab[cursor].onDraw, 0);
                },
                error: function(msg) {
                    _last_router = "";
                    $("#main-content").html("");
                    //$("#main-content").fadeIn(200);
                }
            });
        }
    });
    $.getJSON("api/Router.json?r=" + Math.random(), function(result) {
        _router_tab = result;
        $(window).hashchange();
        login_switch();
    }).error(function() {
        alert("Connection fault detected while loading router table.");
    });
});

/* Common module ver.20130115
-------------------------------------------------- */
function global_parseResult(id) {
    switch(id) {
    case 0:
        return "Accepted";
        break;
    case 1:
        return "Presentation Error";
        break;
    case 2:
        return "Wrong Answer";
        break;
    case 3:
        return "Runtime Error";
        break;
    case 4:
        return "Time Limit Exceeded";
        break;
    case 5:
        return "Memory Limit Exceeded";
        break;
    case 6:
        return "Compilation Error";
        break;
    case 7:
        return "Running";
        break;
    default:
        return "Sent to judge";
        break;
    }
}

/* Blog module ver.20130114
-------------------------------------------------- */

/* Status module ver.20130115
-------------------------------------------------- */
function status_init() {
    status_retrieveData();
    // Set auto refresh interval
    _timer = setInterval("status_retrieveData()", 10000);
}

function status_retrieveData() {
    $("#status-present").html("<i class=\"icon-arrow-down\"></i> \
        Retrieving data...Please wait...");
    var retData = $.getJSON("api/ListStatus.json?r=" + Math.random() + _ajax_parameter, function(result) {
        status_onDraw(result.status);
        status_presentResult(0);
    }).error(function() {
        status_presentResult(1);
    });
}

function status_presentResult(result) {
    switch(result) {
    case 0:
        var d = new Date()
        var ts = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
        $("#status-present").html("<i class=\"icon-ok\"></i> \
                Connected to remote server. Data has been parsed at " + ts);
        break;
    default:
        $("#status-present").html("<i class=\"icon-remove\"></i> \
                Cannot connect to remote server. Try to refresh later.");
        break;
    }
}

function status_colorSheet(id, iseven) {
    var str;
    switch(id) {
    case 0:
        str = "success";
        break;
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
        str = "error";
        break;
    default:
        str = "info";
        break;
    }
    if(iseven & 1) str += "-even";
    return str;
}

function status_filter() {
    _ajax_parameter = "&";
}

function status_onDraw(data) {
    // Display datasheet
    $("#status-details").empty();
    for(i in data) {
        $("#status-details").append("<tr class=\"" + status_colorSheet(data[i].status, i) + "\"> \
                    <td>" + data[i].id + "</td> \
                    <td>" + data[i].author + "</td> \
                    <td>" + data[i].pid + "</td> \
                    <td>" + global_parseResult(data[i].status) + "</td> \
                    <td>" + data[i].time + " MS</td> \
                    <td>" + data[i].mem + " K</td> \
                    <td>" + data[i].ext + "</td> \
                    <td>2012-12-25 22:57:52</td> \
                  </tr>");
    }
}

/* Submit module ver.20130114
-------------------------------------------------- */
function submit_init() {
    var pid = queryString("id");
    if(pid !== undefined) $("#pid").val(pid);
    editor = ace.edit("editor");
    editor.setTheme("ace/theme/tomorrow");
    editor.getSession().setMode("ace/mode/c_cpp");
}

function submit_validInput() {
    var res = 0;
    if(isNaN($("#pid").val())) {
        res |= 1;
    } else {
        var num = parseInt($("#pid").val());
        if(!inRange(num, 1000, 9999)) res |= 1;
    }
    if(!inRange(editor.getValue().length, 50, 65536)) res |= 2;
    res |= 8;
    return res;
}

function submit_post() {
    var res;
    if(!(res = submit_validInput())) {
        $("#submit").attr("disabled", "disabled");
    } else {
        var lang = $("#language").find("option:selected").text();

    }
    submit_presentInfos(res);
}

function submit_presentInfos(id) {
    if(!id) {
        $("#alert-container").html("<div class=\"alert alert-success\"> \
                <strong>Congratulations</strong><br> \
                <li>Your solution was successfully submitted. \
                You'll redirect to status page in 5 seconds, \
                or <a href=\"#status\">click here</a> manually.</li> \
              </div>");
        setTimeout("window.location.href=\"#status\"", 5000);
    } else {
        var dd = "";
        if(id & 1) dd += "<li>Invalid problem identifier. Problem ID should consists of four digits.</li>";
        if(id & 2) dd += "<li>Code length is improper. Make sure your code length is longer than 50 and not exceed 65536 bytes.</li>";
        if(id & 4) dd += "<li>Your operation is too frequently. Please have a rest. :-)</li>";
        if(id & 8) dd += "<li>You haven't logined yet. Click on Login button in the top right corner of the page.</li>";
        $("#alert-container").html("<div class=\"alert alert-error\"> \
                  <strong>Unsuccessful attempt</strong><br>" + dd + "</div>");
    }
}

/* Showcontest module ver.20130115
-------------------------------------------------- */
function showcnt_init() {
    var cid = queryString("cid");
    if(cid === undefined) {
        $("#infoText").text("Wrong contest id. Check url parameter please.");
    }
    $.getJSON("api/ContestDetails.json?cid=106" + Math.random(), function(result) {
        if(!showcnt_authorization(result) || cid === undefined) {
            $("#modalInfo").modal("show");
            $("#modalInfo").on("hidden", function() {
                window.history.back(-1);
            });
        } else {
            showcnt_onDraw();
        }
    });
}

function showcnt_authorization(result) {
    if(result.type == "limited") {
        return showcnt_validUser(result.cid);
    }
    return true;
}

function showcnt_validUser(cid) {
    // has problem
    var flag;
    $.getJSON("api/AuthContest.json?cid=" + cid + Math.random(), function(result) {
        $("#infoText").text(result.log);
        flag = result.attempt;
    });
    return flag;
}

function showcnt_loginAttempt(cid) {

}

function showcnt_onDraw() {
    // alert("OK!");
    // 绘制界面过程
}

/* Showcontest module ver.20130117
-------------------------------------------------- */
function login_showModal() {
    $("#loginModal").modal("show");
}

function login_request() {
    var inp_name = $("#inputUsername").val();
    var inp_pass = $("#inputPassword").val();
    var inp_cook = $("#inputPassword").val();
    $.post("api/LoginHandler.asp?action=post&r=" + Math.random(),
        { username: inp_name, password: inp_pass, remember: inp_cook },
        function(data) {
            alert(data);
            login_switch();
        });
}

function login_switch() {
    
}